from io import BytesIO
import os
import subprocess
import requests
import zipfile


def writeFile(zip: zipfile.ZipFile, name: str):
    data = zip.read("ffmpeg-N-103313-ga1094eaa30-win64-lgpl-shared/bin/"+name)
    with open("C:\\ffmpeg\\"+name, "wb") as f:
        f.write(data)


def writeEnv():
    a = str(subprocess.check_output(
        ["powershell", "(Get-Item HKCU:\Environment).GetValue(\"Path\",$null,\"DoNotExpandEnvironmentNames\")"]), "utf-8").strip("\r\n")
    if(a.endswith(";")):
        a += "C:\\ffmpeg;"
    else:
        a += ";C:\\ffmpeg;"
    subprocess.Popen(
        ["powershell", " [environment]::SetEnvironmentVariable(\"Path\",\""+a+"\",\"User\")"]).wait()


url = "https://hub.fastgit.org/BtbN/FFmpeg-Builds/releases/download/autobuild-2021-08-21-12-22/ffmpeg-N-103313-ga1094eaa30-win64-lgpl-shared.zip"
req = requests.get(url, stream=True)
data = BytesIO()
for chunk in req.iter_content(1048576):
    if chunk:
        data.write(chunk)

if not os.path.exists("C:\\ffmpeg"):
    os.mkdir("C:\\ffmpeg")
zip = zipfile.ZipFile(data)
names = ["avcodec-59.dll", "avdevice-59.dll", "avfilter-8.dll", "avformat-59.dll",
         "avutil-57.dll", "ffmpeg.exe", "ffplay.exe", "ffprobe.exe", "swresample-4.dll", "swscale-6.dll"]
for name in names:
    writeFile(zip, name)
writeEnv()